<?php
/**
 * Author: Administrator
 * Date: 2022/8/4 1:09
 */

namespace DesignPatterns\Behavioral\Visitor;


class PlayerVisitor implements VisitorInterface
{
    private $life;
    private $maxLife;

    public function __construct($life, $remaining = null)
    {
        $this->maxLife = $life;
        $this->life = $remaining ?: $this->maxLife;
    }

    public function visitEnemy(Enemy $enemy)
    {
        $damage = $enemy->getDamage();
        $this->life -= $damage;
        if ($this->life <= 0) {
            $this->die();
        }
        printf('Taking %d damage from enemy <%s>, remaining health %d', $damage, $enemy->getName(), $this->life);
    }

    public function visitFriend(Friend $friend)
    {
        $heals = $friend->getHeal();
        $previous = $this->life;
        $this->life += $heals;
        if ($this->life > $this->maxLife) {
            $this->life = $this->maxLife;
            $heals = $this->life - $previous;
        }
        printf('Healing %d from friend <%s>, remaining health %d', $heals, $friend->getName(), $this->life);
    }

    public function visitEdge(Edge $edge)
    {
        $position = $edge->getPosition();
        $turnOver = [
            'left' => 'right',
            'right' => 'left',
            'top' => 'down',
            'bottom' => 'up'
        ][$position];
        printf('Reaching edge %s, turn %s'.PHP_EOL, $position, $turnOver);
    }

    private function die() {
        $this->life = 0;
        printf('Player dead.');
    }
}